package service

import (
	"errors"
	"geektime-go/week2/homework/domain"
	"geektime-go/week2/homework/repository"
	"golang.org/x/crypto/bcrypt"
)

var ErrInvalidUserOrPassword = errors.New("邮箱或者密码不正确")

type UserService struct {
	repository *repository.UserRepo
}

func NewUserService(repo *repository.UserRepo) *UserService {
	return &UserService{
		repository: repo,
	}
}

func (svc *UserService) SignUp(user domain.User) error {
	// 密码加密
	hash, err := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost)
	if err != nil {
		return err
	}
	user.Password = string(hash)
	return svc.repository.Create(user)
}

func (svc *UserService) Login(email, password string) (domain.User, error) {
	user, err := svc.repository.FindByEmail(email)
	if err != nil {
		return domain.User{}, ErrInvalidUserOrPassword
	}
	err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))
	if err != nil {
		return domain.User{}, ErrInvalidUserOrPassword
	}
	return user, nil
}

func (svc *UserService) Profile(id int64) (domain.User, error) {
	return svc.repository.FindById(id)
}

func (svc *UserService) Edit(user domain.User) error {
	effectRow, err := svc.repository.Update(user)
	if err != nil {
		return err
	}
	if effectRow == 0 {
		return errors.New("用户不存在")
	}
	return nil
}
